import { effect, track, createDepsMap, trigger } from "./effect";
import { Ref } from "./ref";
import { isFunction } from "../utils";

/** 
 * 计算属性
 * @param getter {Function} 监听的方法（需返回值）
 * @return {Ref} 返回一个ref对象
 */
export function computed<T>(getter: () => T): Ref<T> {
    if (!isFunction(getter)) { // getter必须是个方法
        console.error(`computed参数必须是个方法`);
        return
    }

    let value = getter()
    let depsMap = createDepsMap()
    function computedEffect() { value = getter(); trigger(depsMap, 'value') }
    let computed = {
        __v_isRef: true as true,
        get value() {
            track(depsMap, 'value')
            return value
        },
        set value(newVal) {
            console.error('computed 属性不可修改')
        }
    }
    effect(computedEffect) // 监听方法
    return computed
}